/*******************************************************************************
 * Package: com.song.boot.springstudy.thread.lock
 * Type:    A
 * Date:    2022-05-30 20:50
 *
 * 
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 功能描述：玩Lock
 *
 * @author Songxianyang
 * @date 2022-05-30 20:50
 */
public class LockTest {
    
   private ReentrantLock lock = new ReentrantLock();
    
    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        //new Thread(()->{
        //    lockTest.lockReentrantLock();
        //}).start();
       Thread thread= new Thread(()->{
           try {
               lockTest.tryLockTest();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       });
        thread.start();
        new Thread(()->{
            try {
                lockTest.tryLockTest();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
    
    private  void lockReentrantLock() {
        lock.lock();
        try {
            System.out.println("我获取这这把锁---哈哈  开心"+Thread.currentThread().getName());
        } finally {
            lock.unlock();
        }
    }
    
    private void tryLockTest() throws InterruptedException {
        //lock.lock();
        if (lock.tryLock()) {
            try {
                Thread.sleep(1000);
                System.out.println("tryLock判断是否获取锁如果获取到了 就返回true，否则就返回false" + Thread.currentThread().getName());
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                lock.unlock();
                System.out.println("释放锁");
            }
        } else {
            System.out.println("如果没有获取锁则打印这句");
        }
    }
}
